package com.haizi.battery.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.haizi.battery.config.exception.BaseException;
import com.haizi.battery.entity.constant.PreConstant;
import com.haizi.battery.service.busi.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 防止重复提交拦截器
 * 
 * @author ruoyi
 */
@Component
public class AppApiInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AppUserService appUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        AppApi annotation = method.getDeclaringClass().getAnnotation(AppApi.class);
        if (annotation == null) {
            return true;
        }
        NoAuth noToken = method.getAnnotation(NoAuth.class);
        if (noToken != null) {
            return true;
        }
        if (this.noAuth(request)) {
            throw new BaseException("用户尚未授权", 401);
        }
        return true;
    }

    /**
     * 用户授权情况，此处暂时使用小程序的sessionKey作为小程序的token
     * @param request 请求
     * @return 用户是否已授权
     */
    private boolean noAuth(HttpServletRequest request) {
        String sessionKey = request.getHeader("sessionKey");
        if (StrUtil.isEmpty(sessionKey)) {
            return true;
        }
        Integer userId = appUserService.getAppUserBySession(sessionKey);
        boolean result = (null == userId);
        if (null != userId) {
            request.setAttribute(PreConstant.CURRENT_APP_USER, userId);
        }
        return result;
    }


}
